package top.roadvast.rabbitmq.consumer;

import com.rabbitmq.client.*;
import org.springframework.boot.test.context.SpringBootTest;
import top.roadvast.rabbitmq.utils.RabbitmqUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @Author 郭泽鹏
 * @Date 2021/12/27 11:48
 * @Version 1.0
 * @Description 多重绑定，通过手动输入实现动态打印日志级别
 */
@SpringBootTest
public class DirectConsumer {
    public static void main(String[] args) throws IOException {
        final Connection connection = RabbitmqUtil.getConnection();
        final Channel channel = connection.createChannel();
        channel.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);
        String queueName = channel.queueDeclare().getQueue();
        System.out.println("输入要打印的日志级别，日志级别间用\",\"分隔开");
        final String levelStr = new Scanner(System.in).nextLine();
        final String[] levels = levelStr.split(",");
        //把该队列通过 routingKey 绑定到 direct_logs 交换机
        for (String level : levels) {
            if ("info".equalsIgnoreCase(level.trim()) || "warning".equalsIgnoreCase(level.trim()) ||
                    "error".equalsIgnoreCase(level.trim()))
                channel.queueBind(queueName, "direct_logs", level.trim());
        }
        System.out.println("等待接收数据...");
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            System.out.println("接收到消息：" + msg);
        };

        CancelCallback cancelCallback = (consumerTag) -> {

        };

        channel.basicConsume(queueName, true, deliverCallback, cancelCallback);
    }
}
